#include "fdfs_api.h"
#include <stdio.h>
#include "make_log.h"
#include "mysql_conn.h"
#include "cfg.h"
#include <sys/time.h>
#include "utils.h"
#include "cJSON.h"
#include "fcgi_stdio.h"
#include <string.h>

#define SQL_MAX_LEN 1024

int user_register(char* reg_buf);
int get_reg_info(char* reg_buf, char* user, char* nick_name, char* pwd, char* tel, char* email);

int main()
{
    while(FCGI_Accept() >= 0)
    {
        char* contentLength = getenv("CONTENT_LENGTH");
        int len;

        printf("Content-type: text/html; charset=utf8\r\n\r\n");
        
        if(contentLength == NULL) len = -1;
        else len = atoi(contentLength);

        if(len <= 0)
        {
            printf("No data from standard inpu%dt.<p>\n",len+2);
            LOG("len = 0, No data from standard input.\n");
        }
        else
        {
            char buf[1024 * 4] = {0};
            int ret = 0;
            char* out = NULL;
            ret = fread(buf, 1, len, stdin);
            if(ret == 0)
            {
                LOG("fread(buf, 1, len, stdin) err\n");
                printf("没发送有数据");
                continue;
            }
            LOG("buf = %s\n", buf);

            //注册有用户，成功返回0，失败返回-1.用户存在返回-2
            /*
            注册:
                成功：{"code":"002"}
                用户存在：{"code":"003"}
                失败：{"code":"004"}
            */
            ret = user_register(buf);
            if(ret == 0)//注册成功
            {
                out = return_status("002");
            }
            else if(ret == -1)
            {
                out = return_status("004");
            }
            else if(ret == -2)
            {
                out = return_status("003");
            }

            if(out != NULL)
            {
                printf(out);
                free(out);
            }
        }
    }
}

int user_register(char* reg_buf)
{
    int ret = 0;
    MYSQL* conn = NULL;

    //获取数据库用户名、用户密码、数据库标示等信息
    char mysql_user[256] = {0};
    char mysql_pwd[256] = {0};
    char mysql_db[256] = {0};
    ret = get_mysql_info(mysql_user, mysql_pwd, mysql_db);
    if(ret != 0)
    {
        goto END;
    }
    LOG("mysql_user = %s, mysql_pwd = %s, mysql_db= %s\n", mysql_user, mysql_pwd, mysql_db);

    //获取注册用户的信息
    char user[128];
    char nick_name[128];
    char pwd[128];
    char tel[128];
    char email[128];
    ret = get_reg_info(reg_buf, user, nick_name, pwd, tel, email);
    if(ret != 0)
    {
        goto END;
    }
    LOG("user = %s, nick_name = %s, pwd = %s, tel = %s, email = %s\n", user, nick_name, pwd, tel, email);

    conn = get_mysql(mysql_user, mysql_pwd, mysql_db);
    if(conn == NULL)
    {
        LOG("get_mysql err\n");
        ret = -1;
        goto END;
    }

    // mysql_query(conn, "ser names utf8mb4"); 本就是utf8mb4

    char sql_cmd[SQL_MAX_LEN] = {0};

    sprintf(sql_cmd, "select* from user_info where user_name = '%s';", user);

    int ret2 = 0;
    ret2 = process_result_one(conn, sql_cmd, NULL);
    if(ret2 == 2) //已存在
    {
        LOG("[%s]该用户已存在\n", user);
        ret = -2;
        goto END;
    }
    else if(ret2 == -1)
    {
        LOG("process_result_one error#mysql_query err\n");
        ret = -1;
        goto END;
    }
    //添加
     else if(ret2 == -2)
    {
        LOG("process_result_one error mysql_store_result error\n");
        ret = -1;
        goto END;
    }

    //当前时间戳
    struct timeval tv;
    struct tm* ptm;
    char time_str[128];

    gettimeofday(&tv, NULL);
    ptm = localtime(&tv.tv_sec);
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", ptm);

    sprintf(sql_cmd, "insert into user_info(user_name, nick_name, password, phone, create_time, email) values('%s', '%s', '%s', '%s', '%s', '%s')", user, nick_name, pwd, tel, time_str, email);

    if(mysql_query(conn, sql_cmd) != 0)
    {
        LOG("插入失败：%s, %s\n", mysql_error(conn), sql_cmd);
        ret = -1;
        goto END;
    }
END:
    if(conn != NULL)
    {
        mysql_close(conn);
    }

    return ret;
}

int get_reg_info(char* reg_buf, char* user, char* nick_name, char* pwd, char* tel, char* email)
{
    int ret = 0;
    cJSON* root = cJSON_Parse(reg_buf);
    if(root == NULL)
    {
        LOG("root error\n");
        ret = -1;
        goto END;
    }

    cJSON* userName = cJSON_GetObjectItem(root, "userName");
    if(userName == NULL)
    {
        cJSON_Delete(root);
        LOG("userName error\n");
        ret = -1;
        goto END;
    }

    cJSON* nickName = cJSON_GetObjectItem(root, "nickName");
    if(nickName == NULL)
    {
        cJSON_Delete(root);
        LOG("nickName error\n");
        ret = -1;
        goto END;
    }

    cJSON* firstPwd = cJSON_GetObjectItem(root, "firstPwd");
    if(firstPwd == NULL)
    {
        cJSON_Delete(root);
        LOG("firstPwd error\n");
        ret = -1;
        goto END;
    }

    cJSON* phone = cJSON_GetObjectItem(root, "phone");
    if(phone == NULL)
    {
        cJSON_Delete(root);
        LOG("phone error\n");
        ret = -1;
        goto END;
    }

    cJSON* em = cJSON_GetObjectItem(root, "email");
    if(em == NULL)
    {
        cJSON_Delete(root);
        LOG("em error\n");
        ret = -1;
        goto END;
    }

    strcpy(user, userName->valuestring);
    strcpy(nick_name, nickName->valuestring);
    strcpy(pwd, firstPwd->valuestring);
    strcpy(tel, phone->valuestring);
    strcpy(email, em->valuestring);

    cJSON_Delete(root);
END:
    return ret;
}
